package cn.qinhao.pethome.login.service.impl;

import cn.qinhao.pethome.basic.exception.BusinessException;
import cn.qinhao.pethome.basic.until.MD5Utils;
import cn.qinhao.pethome.basic.until.StrUtils;
import cn.qinhao.pethome.login.domain.LoginVo;
import cn.qinhao.pethome.login.domain.Logininfo;
import cn.qinhao.pethome.login.mapper.LogininfoMapper;
import cn.qinhao.pethome.login.service.ILogininfoService;
import cn.qinhao.pethome.basic.base.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author qinhao
 * @since 2023-02-28
 */
@Service
public class LogininfoServiceImpl extends BaseServiceImpl<Logininfo> implements ILogininfoService {
    @Autowired
    private LogininfoMapper logininfoMapper;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public String  login(LoginVo loginVo) {
        //校验参数
        if(loginVo.getPassword()==null){
            throw new BusinessException("密码不能为空");
        }
        if(loginVo.getUsername()==null){
            throw new BusinessException("用户名不能为空");
        }
        if(loginVo.getType()==null){//前端设置了值，但进来又没有，说明同行在用postman等工具进来
            throw new BusinessException("同行请绕行");
        }
        //数据库验证   支持 手机号  邮箱  用户名
        Logininfo logininfo = logininfoMapper.loadByUsernames(loginVo);
        if(logininfo==null){
            throw new BusinessException("用户名或者密码输入错误");
        }
        //密码比较
        String password =loginVo.getPassword();
        String salt = logininfo.getSalt();
        String passwordSalt=password;//是第三方就加密
        if(!loginVo.getIsThree()){//不是第三方就加密
            //给传进来得密码加密加盐
            passwordSalt = MD5Utils.encrypByMd5(password + salt);
        }

        if(!logininfo.getPassword().equals(passwordSalt)){
            throw new BusinessException("用户名或者密码输入错误");
        }
        //生成token传回前端存储
        String token = StrUtils.getComplexRandomString(32);
        //以token为键，登录信息为值保存到redis
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        //返回前端
        return token;
    }
}
